package com.goldsprite.microhorigame.screens.examples.simplephysexamples;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.goldsprite.gameframeworks.log.Debug;
import com.goldsprite.gameframeworks.screens.GScreen;
import com.goldsprite.gameframeworks.utils.math.Vector2;
import com.goldsprite.gameframeworks.simplephys.collis.CollisionResult;
import com.goldsprite.gameframeworks.simplephys.collis.CollisionUtils;

import java.util.ArrayList;
import java.util.List;

public class CollisionDemoScreen extends GScreen {

	private OrthographicCamera camera;
	private ShapeRenderer shapeRenderer;

	// 测试实体
	private List<DemoEntity> entities;
	private DemoEntity playerEntity;
	private DemoEntity staticEntity;

	// 控制变量
	private boolean showNormals = true;
	private boolean showOverlap = true;

	@Override
	public void create() {
		camera = getCamera();
		shapeRenderer = new ShapeRenderer();

		entities = new ArrayList<>();

		// 创建玩家控制的实体
		playerEntity = new DemoEntity(100, 100, 50, 50, Color.BLUE);
		playerEntity.velocity.set(200, 150); // 初始速度

		// 创建静态测试实体
		staticEntity = new DemoEntity(400, 300, 80, 60, Color.RED);
		staticEntity.isStatic = true;

		// 添加一些随机实体
		entities.add(playerEntity);
		entities.add(staticEntity);
		entities.add(new DemoEntity(200, 400, 40, 40, Color.GREEN));
		entities.add(new DemoEntity(500, 200, 60, 80, Color.ORANGE));
		entities.add(new DemoEntity(300, 100, 70, 50, Color.PURPLE));
	}

	@Override
	public void show() {
		super.show();
		Debug.logT("CollisionDemo", "碰撞演示屏幕已启动");
		Debug.logT("CollisionDemo", "控制说明: WASD移动, 空格重置, N切换法线显示, O切换重叠显示");
	}

	@Override
	public void render0(float delta) {
		handleInput();
		update(delta);

		// 开始绘制
		shapeRenderer.setProjectionMatrix(camera.combined);

		// 绘制所有实体
		shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
		for (DemoEntity entity : entities) {
			entity.render(shapeRenderer);
		}
		shapeRenderer.end();

		// 绘制边框和法线
		shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
		for (DemoEntity entity : entities) {
			entity.renderBorder(shapeRenderer);
		}
		shapeRenderer.end();

		// 绘制重叠区域
		if (showOverlap) {
			drawOverlapAreas();
		}
	}

	private void handleInput() {
		// 玩家控制
		float speed = 300;
		playerEntity.velocity.set(0, 0);

		if (Gdx.input.isKeyPressed(Input.Keys.W)) playerEntity.velocity.y = speed;
		if (Gdx.input.isKeyPressed(Input.Keys.S)) playerEntity.velocity.y = -speed;
		if (Gdx.input.isKeyPressed(Input.Keys.A)) playerEntity.velocity.x = -speed;
		if (Gdx.input.isKeyPressed(Input.Keys.D)) playerEntity.velocity.x = speed;

		// 切换显示选项
		if (Gdx.input.isKeyJustPressed(Input.Keys.N)) {
			showNormals = !showNormals;
		}
		if (Gdx.input.isKeyJustPressed(Input.Keys.O)) {
			showOverlap = !showOverlap;
		}

		// 重置位置
		if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
			playerEntity.bounds.setPosition(100, 100);
			playerEntity.velocity.set(200, 150);
		}
	}

	private void update(float delta) {
		// 更新所有非静态实体
		for (DemoEntity entity : entities) {
			if (!entity.isStatic) {
				entity.update(delta, (List<GameEntity>)(List<?>)entities);
			}
		}

		// 边界检查
		for (DemoEntity entity : entities) {
			// 使用 clamp 限制位置在屏幕范围内
			float clampedX = MathUtils.clamp(entity.bounds.x, 0, getViewSize().x - entity.bounds.width);
			float clampedY = MathUtils.clamp(entity.bounds.y, 0, getViewSize().y - entity.bounds.height);
			entity.bounds.setPosition(clampedX, clampedY);
		}
	}

	private void drawCollisionNormal(GameEntity entity, CollisionResult result) {
		Vector2 center = new Vector2(
			entity.bounds.x + entity.bounds.width / 2,
			entity.bounds.y + entity.bounds.height / 2
		);

		Vector2 normalEnd = new Vector2(center)
			.add(result.normal.x * 30, result.normal.y * 30);

		shapeRenderer.setColor(Color.YELLOW);
		shapeRenderer.line(center.x, center.y, normalEnd.x, normalEnd.y);

		// 绘制法线箭头
		drawArrow(center.x, center.y, normalEnd.x, normalEnd.y);
	}

	private void drawArrow(float x1, float y1, float x2, float y2) {
		float arrowLength = 10;
		float arrowAngle = (float) Math.toRadians(30);

		float angle = (float) Math.atan2(y2 - y1, x2 - x1);

		// 箭头两侧的线
		float x3 = x2 - arrowLength * (float) Math.cos(angle - arrowAngle);
		float y3 = y2 - arrowLength * (float) Math.sin(angle - arrowAngle);
		float x4 = x2 - arrowLength * (float) Math.cos(angle + arrowAngle);
		float y4 = y2 - arrowLength * (float) Math.sin(angle + arrowAngle);

		shapeRenderer.line(x2, y2, x3, y3);
		shapeRenderer.line(x2, y2, x4, y4);
	}

	private void drawOverlapAreas() {
		shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

		for (int i = 0; i < entities.size(); i++) {
			for (int j = i + 1; j < entities.size(); j++) {
				DemoEntity a = entities.get(i);
				DemoEntity b = entities.get(j);

				CollisionResult result = new CollisionResult();
				if (CollisionUtils.calculateCollision(a.bounds, b.bounds, result) && result.collided) {
					// 计算重叠区域
					float overlapX = Math.min(a.bounds.x + a.bounds.width, b.bounds.x + b.bounds.width)
						- Math.max(a.bounds.x, b.bounds.x);
					float overlapY = Math.min(a.bounds.y + a.bounds.height, b.bounds.y + b.bounds.height)
						- Math.max(a.bounds.y, b.bounds.y);

					float overlapXStart = Math.max(a.bounds.x, b.bounds.x);
					float overlapYStart = Math.max(a.bounds.y, b.bounds.y);

					// 绘制半透明的重叠区域
					shapeRenderer.setColor(1, 1, 0, 0.3f);
					shapeRenderer.rect(overlapXStart, overlapYStart, overlapX, overlapY);
				}
			}
		}

		shapeRenderer.end();
	}

	@Override
	public void dispose() {
		shapeRenderer.dispose();
	}

	// 演示用的实体类
	private static class DemoEntity extends GameEntity {
		public Color color;
		public boolean isStatic;

		public DemoEntity(float x, float y, float width, float height, Color color) {
			this.bounds.set(x, y, width, height);
			this.color = color;
		}

		Color tmpColor = new Color();
		public void render(ShapeRenderer shapeRenderer) {
			Color color = tmpColor.set(isCollied() ? Color.CYAN : this.color);
			color.a = 0;
			shapeRenderer.setColor(color);
			shapeRenderer.rect(bounds.x, bounds.y, bounds.width, bounds.height);
		}

		public void renderBorder(ShapeRenderer shapeRenderer) {
			shapeRenderer.setColor(isStatic ? Color.BLACK : Color.WHITE);
			shapeRenderer.rect(bounds.x, bounds.y, bounds.width, bounds.height);
		}

		@Override
		public void update(float delta, List<GameEntity> others) {
			boolean isMoving = !velocity.isZero();
			if (!isStatic && isMoving) {
				super.update(delta, others);
			}
		}

		@Override
		protected void collisionBlock(GameEntity other, CollisionResult result) {
			super.collisionBlock(other, result);
		}
	}
}
